package org.sean.framework.web.service;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.sean.framework.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;

/**
 * Date: 2016/10/27 11:38
 *
 * @author Sean.xie
 */
public class FreeMarkerService {
    private Logger logger = Logger.newInstance(FreeMarkerService.class);

    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;

    public FreeMarkerService(FreeMarkerConfigurer freeMarkerConfigurer) {
        this.freeMarkerConfigurer = freeMarkerConfigurer;
    }

    /**
     * 生成模板内容
     * <pre>
     * example:
     * 从templates目录下获取模板
     * getTemplateContent("demo.flt",obj);
     * 从templates/test目录下获取模板
     * getTemplateContent("test/demo.flt",obj);
     * </pre>
     *
     * @param <T>          T
     * @param templateName 模板文件目录 根目录为 resources/templates
     * @param t            实体
     * @return 模板内容
     */
    public <T> String getTemplateContent(String templateName, T t) {
        try (
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(bos))
        ) {
            Configuration configuration = freeMarkerConfigurer.getConfiguration();
            configuration.getTemplateLoader();
            Template template = configuration.getTemplate(templateName);
            template.process(t, bw);
            return bos.toString();
        } catch (IOException | TemplateException e) {
            logger.printStackTrace(e);
            return null;
        }
    }
}
